package com.example.cloud.service.personal.impl;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.personal.WorkOrderRepository;
import com.example.cloud.model.personal.WorkOrder;
import com.example.cloud.model.system.User;
import com.example.cloud.service.personal.WorkOrderService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Created by wangtao on 2018/5/22.
 */
@Service
public class WorkOrderServiceImpl implements WorkOrderService {

    @Autowired
    EntityManager em;

    @Autowired
    SQLManager sqlManager;

    @Autowired
    private WorkOrderRepository workOrderRepository;

    @Override
    public List<WorkOrder> findListdByUser() {
        User user = RequestUtil.getLoginUser();
        StringBuilder sql = new StringBuilder("select * from work_order where process_user_id = :userId and `status` in (:status) and delete_flag = 0");
        Query nativeQuery = em.createNativeQuery(sql.toString(), WorkOrder.class);
//        nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        nativeQuery.setParameter("userId", user.getId());
        Integer[] status = new Integer[]{StateConstants.WORK_ORDER_STATUS_NEW, StateConstants.WORK_ORDER_STATUS_PROCESS};
        nativeQuery.setParameter("status", status);
        return nativeQuery.getResultList();
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doSave(WorkOrder record) throws ParseException {
        User loginUser = RequestUtil.getLoginUser();
        record.setSubmitUserId(loginUser.getId());
        record.setSubmitUserName(loginUser.getUsername());
        record.setAccountId(loginUser.getAccountId());
        record.setOrganId(loginUser.getOrganId());
        record.setOrganName(loginUser.getOrganName());
        if(StringUtils.isNotBlank(record.getRequireCompleteTimeStr())){
            record.setRequireCompleteTime(DateUtils.parseDate(record.getRequireCompleteTimeStr(), CommonConstants.DATE_FORMATS));
        }
        BusinessUtil.appendRecord(record);
        workOrderRepository.save(record);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doAccept(WorkOrder record) throws ParseException {
        record.setAcceptTime(new Date());
        record.setStatus(StateConstants.WORK_ORDER_STATUS_PROCESS);
        if(StringUtils.isNotBlank(record.getExpectCompleteTimeStr())){
            record.setExpectCompleteTime(DateUtils.parseDate(record.getExpectCompleteTimeStr(), CommonConstants.DATE_FORMATS));
        }else{
            record.setExpectCompleteTime(record.getRequireCompleteTime());
        }
        BusinessUtil.appendRecord(record);
        workOrderRepository.save(record);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doResolve(Long id) {
        // 实际完成时间
        Date actualCompleteTime = new Date();
        WorkOrder workOrder = workOrderRepository.findOne(id);
        // 答复完成时间
        Date expectCompleteTime = workOrder.getExpectCompleteTime();
        // 实际完成时间在答复完成时间内
        if(actualCompleteTime.compareTo(expectCompleteTime) <= 0){
            workOrder.setTimeComplete(StateConstants.TIME_COMPLETE_YES);
        }else{
            workOrder.setTimeComplete(StateConstants.TIME_COMPLETE_NO);
        }
        workOrder.setStatus(StateConstants.WORK_ORDER_STATUS_PROCESSED);
        workOrder.setActualCompleteTime(actualCompleteTime);
        BusinessUtil.appendRecord(workOrder);
        workOrderRepository.save(workOrder);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doAuditComplete(Long id) {
        StringBuilder sql = new StringBuilder("update work_order set `status` = :status,audit_complete_time = SYSDATE() where id = :id");
        Query nativeQuery = em.createNativeQuery(sql.toString());
        nativeQuery.setParameter("status", StateConstants.WORK_ORDER_STATUS_COMPLETE);
        nativeQuery.setParameter("id", id);
        nativeQuery.executeUpdate();
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doDelete(List<Long> ids) {
        workOrderRepository.deleteByIdIn(ids);
    }
}
